import { defineStore } from 'pinia'
import { ref } from 'vue'
import { mergeCartList } from '@/api/cart.js'
import { login } from '@/api/user.js'
import { useCartStore } from '@/stores/modules/cart.js'

export const useUserStore = defineStore(
  'xtx-user',
  () => {
    const token = ref('')
    const user = ref({})
    const cartStore = useCartStore()

    // await mergeCartList(useCartStore().cartList.map(item => {
    //   return {
    //     skuId: item.skuId,
    //     count: item.count,
    //     selected: item.selected || true, // 默认选中
    //   }
    // }
    async function getUserInfo({ account, password }) {
      const res = await login({ account, password })
      user.value = res.result
      token.value = res.result.token
      await mergeCartList(useCartStore().cartList.map(item => {
        return {
          skuId: item.skuId,
          count: item.count,
          selected: item.selected || true, // 默认选中
        }
      }))
      await cartStore.refreshCart()
    }

    function setToken(newToken) {
      token.value = newToken
    }

    function removeToken() {
      token.value = ''
    }

    function setUser(newUser) {
      user.value = newUser
    }

    // 清除所有用户数据
    function clearUserInfo() {
      token.value = ''
      user.value = {}
      useCartStore().clearCart()
    }

    return {
      token,
      user,
      setToken,
      removeToken,
      getUserInfo,
      setUser,
      clearUserInfo,
    }
  },
  {
    persist: true,
  },
)
